package com.open.capacity.finance.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.open.capacity.finance.config.Globals;
import com.open.capacity.finance.dao.AuditAnalysisDao;
import com.open.capacity.finance.dao.SourceBaseCustomItemDao;
import com.open.capacity.finance.dao.SourceBaseCustomValueDao;
import com.open.capacity.finance.dao.SourceBaseKjkmExtDao;
import com.open.capacity.finance.dto.AuditModelBaseResult;
import com.open.capacity.finance.dto.audit_model_42.AuditModelResult;
import com.open.capacity.finance.dto.audit_model_42.AuditModelStep1;
import com.open.capacity.finance.dto.audit_model_42.AuditModelStep2;
import com.open.capacity.finance.dto.audit_model_42.ExcelData;
import com.open.capacity.finance.entity.*;
import com.open.capacity.finance.service.AbstractAuditMakeResultFactory;
import com.open.capacity.finance.service.AuditModelRuleService;
import com.open.capacity.finance.service.AuditModelService;
import com.open.capacity.finance.service.SourceBaseBudgetTotal12Service;
import com.open.capacity.finance.util.FileUtil;
import com.open.capacity.utils.StringUtil;
import com.open.capacity.utils.encrypt.Md5Utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class AuditModelActuator42ServiceImpl<T extends AuditModelBaseResult> extends AbstractAuditMakeResultFactory {

    @Autowired
    private AuditAnalysisDao analysisDao;

    @Autowired
    private SourceBaseBudgetTotal12Service budgetTotal12Service;

    @Autowired
    private SourceBaseKjkmExtDao kjkmExtDao;
    @Autowired
    private SourceBaseCustomItemDao customItemDao;
    @Autowired
    private SourceBaseCustomValueDao customValueDao;

    @Autowired
    private AuditModelRuleService ruleService;
    @Autowired
    private AuditModelService modelService;

    private static final String CUSTOMITEMCODE = "EXPECO";


    @Override
    protected T analyseResultData(String modelId, Map param) {
        String companyId = param.containsKey("companyId") ? param.get("companyId").toString() : "";
        param.put("ztId", "101");
        AuditModelResult result = new AuditModelResult();
        AuditModel model = modelService.findById(modelId);
        Assert.notNull(model, "找不到该模型");
        List<AuditModelRule> rules = ruleService.findByModelId(modelId);
        rules.forEach(t -> {
            param.put(t.getConfKey(), t.getConfValue());
        });
        result.setModelName(model.getCodeAndName());


        param.put("jjflcodes", Arrays.asList("30231", "30212", "30217", "31013"));

        List<AuditModelStep2> pzList = analysisDao.model42(param);
        pzList = completeEmptyPzList(pzList);
        List<SourceBaseBudgetTotal12> budgetTotalList = budgetTotal12Service.findAll(param);

        List<AuditModelStep1> step1List = new ArrayList<>();

        HashMap<String, List<AuditModelStep2>> collect = pzList.stream().collect(Collectors.groupingBy(t -> t.getCompanyId() + "_" + "_" + t.getKjnd() + "_" + t.getJjflcode().substring(0, 5) + "_" + t.getJjflname(), HashMap::new, Collectors.toList()));

        AuditModelStep1 step1;
        for (Map.Entry<String, List<AuditModelStep2>> entry : collect.entrySet()) {

            String _companyId = entry.getKey().split("_")[0];
            String companyName = Globals.companyList.stream().filter(company -> company.getId().equals(_companyId)).findFirst().get().getFullName();
            Integer kjnd = Integer.parseInt(entry.getKey().split("_")[2]);
            String jjflcode = entry.getKey().split("_")[3];
            String jjflname = entry.getKey().split("_")[4];
            step1 = new AuditModelStep1();
            step1.setCompanyId(_companyId);
            step1.setCompanyName(companyName);
            step1.setKjnd(kjnd);
            step1.setJjflname(jjflname);
            BigDecimal amount = (entry.getValue().stream().map(t -> t.getJ()).reduce(BigDecimal.ZERO, (a, b) -> a.add(b)));
            step1.setAmount(amount.divide(BigDecimal.valueOf(10000)).setScale(2, BigDecimal.ROUND_HALF_UP));
            step1.setScale(amount.multiply(BigDecimal.valueOf(100)).divide(pzList.stream().filter(t -> t.getCompanyId().equals(_companyId) && t.getKjnd().equals(kjnd)).map(t -> t.getJ()).reduce(BigDecimal.ZERO, (a, b) -> a.add(b)), BigDecimal.ROUND_HALF_UP).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());

            Optional<SourceBaseBudgetTotal12> first = budgetTotalList.stream().filter(t -> t.getCompanyId().equals(_companyId) && t.getKjnd().equals(kjnd) && t.getJjflCode().equals(jjflcode)).findFirst();
            if (first.isPresent() && first.get().getTotalMoney().compareTo(BigDecimal.ZERO) != 0) {
                step1.setBudgetAmount(first.get().getTotalMoney().divide(BigDecimal.valueOf(10000)).setScale(2, BigDecimal.ROUND_HALF_UP));
                step1.setExcutePercent(step1.getAmount().multiply(BigDecimal.valueOf(1000000)).divide(first.get().getTotalMoney(), BigDecimal.ROUND_HALF_UP).doubleValue());
            }

            step1List.add(step1);
        }
        step1List.sort(Comparator.comparing(AuditModelStep1::getCompanyId)
                .thenComparing(AuditModelStep1::getKjnd)
                .thenComparing(AuditModelStep1::getJjflname));

        result.setCompanyId(companyId);

        result.setStep1List(step1List);
        if (CollectionUtils.isEmpty(step1List)) {
            result.setExists(0);
        } else {
            result.setExists(1);

            //持久化本地
            persistence(result);
        }

        return (T) result;
    }


    //补充完整三公，当不存在某个经济分类的凭证时，补充一个0余额凭证
    private List<AuditModelStep2> completeEmptyPzList(List<AuditModelStep2> pzList) {

        List<AuditModelStep2> result = new ArrayList<>();
        HashMap<String, List<AuditModelStep2>> collect = pzList.stream().collect(Collectors.groupingBy(t -> t.getCompanyId() + "_" + t.getKjnd(), HashMap::new, Collectors.toList()));
        for (Map.Entry<String, List<AuditModelStep2>> entry : collect.entrySet()) {
            String companyId = entry.getKey().split("_")[0];
            Integer kjnd = Integer.parseInt(entry.getKey().split("_")[1]);

            for (AuditModelStep2 c : entry.getValue()) {
                if (c.getJjflcode().startsWith("31013") || c.getJjflcode().startsWith("30231")) {
                    c.setJjflcode("30231");
                    c.setJjflname("公务用车运行维护费");
                } else if (c.getJjflcode().startsWith("30217")) {
                    c.setJjflname("公务接待费");
                } else if (c.getJjflcode().startsWith("30212")) {
                    c.setJjflname("因公出国（境）费用");
                }
            }

            if (entry.getValue().stream().filter(t -> t.getJjflcode().contains("30217")).count() == 0) {
                AuditModelStep2 item = new AuditModelStep2();
                item.setCompanyId(companyId);
                item.setKjnd(kjnd);
                item.setJjflcode("30217");
                item.setJjflname("公务接待费");
                item.setJ(BigDecimal.ZERO);
                item.setD(BigDecimal.ZERO);
                entry.getValue().add(item);
            }
            if (entry.getValue().stream().filter(t -> t.getJjflcode().contains("30231")).count() == 0) {
                AuditModelStep2 item = new AuditModelStep2();
                item.setCompanyId(companyId);
                item.setKjnd(kjnd);
                item.setJjflcode("30231");
                item.setJjflname("公务用车运行维护费");
                item.setJ(BigDecimal.ZERO);
                item.setD(BigDecimal.ZERO);
                entry.getValue().add(item);
            }
            if (entry.getValue().stream().filter(t -> t.getJjflcode().contains("30212")).count() == 0) {
                AuditModelStep2 item = new AuditModelStep2();
                item.setCompanyId(companyId);
                item.setKjnd(kjnd);
                item.setJjflcode("30212");
                item.setJjflname("因公出国（境）费用");
                item.setJ(BigDecimal.ZERO);
                item.setD(BigDecimal.ZERO);
                entry.getValue().add(item);
            }
            result.addAll(entry.getValue());
        }
        return result;
    }

    @Override
    protected int persistence(AuditModelBaseResult data) {
        int result = 0;

        String content = JSON.toJSONString(data, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteDateUseDateFormat);

        data.setResultFileMd5(Md5Utils.hash(content));
        data.setResultFileUrl("/upload/analyse/model42_" + data.getCompanyId() + "_" + data.getResultFileMd5() + ".json");

        Writer write = null;
        try {
            File file = new File(fileuploadPath + "/upload/analyse/model42_" + data.getCompanyId() + "_" + data.getResultFileMd5() + ".json");
            if (file.exists()) {
                file.delete();
            }
            file.createNewFile();
            // 写入文件
            write = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8);
            write.write(content);
            write.flush();
            write.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                write.close();
            } catch (IOException e) {
                log.error(e.getMessage());
            }
        }
        return result;
    }

    @Override
    public T getData(String modelId, Map param) {
        return analyseResultData(modelId, param);
    }


    /**
     * 从本地加载数据
     */
    public AuditModelBaseResult getDataFromJson(String jsonUrl, Map param) {
        AuditModelResult result = null;
        try {
            String json = FileUtil.readTxtToJson(fileuploadPath + jsonUrl);
            result = JSONObject.parseObject(json, new TypeReference<AuditModelResult>() {
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

        filterCondition(result, param);

        return result;
    }

    /**
     * 本地json数据条件过滤
     */
    private AuditModelResult filterCondition(AuditModelResult orig, Map param) {
        AuditModelResult result = orig;
        String companyId = MapUtils.getString(param, "companyId");
        Integer kjnd = MapUtils.getInteger(param, "kjnd");

        List<AuditModelStep1> list = orig.getStep1List();
        if (StringUtil.isNotEmpty(companyId)) {
            list = list.stream().filter(t -> t.getCompanyId().equals(companyId)).collect(Collectors.toList());
        }
        if (kjnd != null) {
            list = list.stream().filter(t -> t.getKjnd().equals(kjnd)).collect(Collectors.toList());
        }

        result.setStep1List(list);

        return result;
    }

    public void exportExcel(String modelId, Map params, HttpServletResponse response) {
        AuditModelResult t = (AuditModelResult) analyseResultData(modelId, params);

        export(t, response);
    }

    @Override
    public void exportExcelFromJson(String modelId, String jsonUrl, HttpServletResponse response) {
        AuditModelResult t = null;
        try {
            String json = FileUtil.readTxtToJson(fileuploadPath + jsonUrl);
            t = JSONObject.parseObject(json, new TypeReference<AuditModelResult>() {
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

        export(t, response);
    }

    private void export(AuditModelResult t, HttpServletResponse response) {
        List<ExcelData> result = t.getStep1List().stream().map(item -> {
            ExcelData model = new ExcelData();
            BeanUtils.copyProperties(item, model);
            return model;
        }).collect(Collectors.toList());

        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment;filename=download_42.xls");
        OutputStream ouputStream = null;
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(),
                ExcelData.class, result);
        try {
            ouputStream = response.getOutputStream();
            workbook.write(ouputStream);
        } catch (Exception e) {
            throw new RuntimeException("系统异常");
        } finally {
            try {
                if (ouputStream != null) {
                    ouputStream.flush();
                    ouputStream.close();
                }
            } catch (Exception e) {
                throw new RuntimeException("系统异常");
            }
        }
    }
}
